<!--
 @description 楼层配置项
 @fileName ItemLIst.vue
 @author zengqiongying
 @created 2022/12/14 09:48:57
-->
<template>
  <div>
    <div slot="table-before" class="qup-title-box item-title">
      <div><span class="border" /><span>楼层内容</span></div>
      <div class="alert-msg"><span v-if="layoutData.maxCount>0">最多新增{{ layoutData.maxCount }}条{{ layoutData.type | filterLayoutType }}数据，</span>按序号排序进行显示。</div>
      <el-button v-if="enbleCreate" size="mini" type="primary" @click="handleEdit">添加</el-button>
    </div>
    <table-box
      ref="refTable"
      :selected-arry.sync="tableSelected"
      :table-config="tableConfig"
      :other-filters="otherFilters"
      :table-max-height="400"
      table-row-key="id"
      :table-sortable="false"
      show-index
      :show-page="Number(layoutData.maxCount || 0)===0"
      @data-change="dataChange"
    />
    <ItemEdit
      v-if="showEdit"
      ref="refEdit"
      :visible.sync="showEdit"
      :detail="activeRowData"
      :floor-id="floorId"
      :layout-data="layoutData"
      :page-data="pageData"
      @success="refreshTable"
    />
  </div>
</template>

<script>
import { FLOOR_TYPE } from '../constData'
import { queryBtnList } from '@/api/permissions'
import { delFloorDetail, updateSort } from '@/api/floorDetail'
import { queryRefCategoryList } from '@/api/floorConf'
import ItemEdit from './ItemEdit'

export default {
  name: 'FloorItemList',
  filters: {
    filterLayoutType(val) {
      return FLOOR_TYPE[val] || ''
    }
  },
  components: { ItemEdit },
  props: {
    pageData: {
      type: Object,
      default: () => {}
    },
    floorId: {
      type: String,
      default: ''
    },
    layoutData: {
      type: [String, Object],
      default: ''
    } // 楼层布局
  },
  data() {
    const that = this
    return {
      showEdit: false,
      tableData: [],
      activeRowData: '', // 当前选中行数据
      tableSelected: [], // 当前所选中表格行数据
      otherFilters: [], // 表格额外查询条件
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/v2FloorDetail/page`,
        tabIndex: 20,
        buttonGroupCode: 'floorDetail',
        hideFuncBar: true,
        pageFlag: Number(this.layoutData.maxCount || 0) === 0,
        sort: 'sort',
        order: 'asc',
        setting: [
          {
            prop: 'pic',
            label: '封面图',
            minWidth: 100,
            overflowHidden: false,
            sortable: false,
            type: 'hidden',
            align: 'center',
            render: (_h, row) => {
              const iconUrl = row.pic || ''
              if (iconUrl) {
                const url = that.formatImageUrl(iconUrl)
                return (<div class='cover-image'><img src={url} /></div>)
              }
              return ''
            }
          },
          {
            prop: 'name',
            label: '名称',
            minWidth: 150
          },
          {
            prop: 'gotoName',
            label: '关联内容',
            minWidth: 250,
            formatData: (row) => {
              return that.gotoContent(row)
            }
          },
          {
            prop: 'sort',
            label: '排序',
            width: 200,
            sortable: false,
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              const btns = []
              if (this.hasPermission('top')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'top')} class='btn-green my-txt-btn'>置顶</el-button>)
              }
              if (this.hasPermission('up')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'moveUp')} class='btn-green my-txt-btn'>上移</el-button>)
              }
              if (this.hasPermission('down')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'moveDown')} class='btn-green my-txt-btn'>下移</el-button>)
              }
              if (this.hasPermission('bottom')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'bottom')} class='btn-green my-txt-btn'>置底</el-button>)
              }
              return _h('div', btns)
            }
          },
          {
            prop: 'opetate',
            label: '操作',
            width: 120,
            sortable: false,
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              const btns = []
              if (this.hasPermission('edit')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleEdit.bind(this, row)} class='btn-green my-txt-btn'>编辑</el-button>)
              }
              if (this.hasPermission('del')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleDelete.bind(this, row)} class='btn-green my-txt-btn'>删除</el-button>)
              }
              return _h('div', btns)
            }
          }
        ],
        btnList: []
      },
      buttons: [],
      sorting: false
    }
  },

  computed: {
    enbleCreate() {
      if (!this.hasPermission('add')) {
        return false
      }
      if (this.tableData && this.layoutData && this.layoutData.maxCount > 0) {
        return this.tableData.length < this.layoutData.maxCount
      }
      return true
    }
  },

  created() {
    if ([0, 1, 2, '0', '1', '2'].includes(this.pageData.id)) {
      const roleCol = {
        prop: 'roleName',
        label: '角色名称',
        minWidth: 150,
        formatData: (row) => {
          const roles = row.roles || []
          return roles && roles.map(v => v.roleName).join(',')
        }
      }
      this.tableConfig.setting.splice(2, 0, roleCol)
    }
    this.otherFilters = [
      { id: 'floorConfId', property: 'floorConfId', operator: '=', value: this.floorId }
    ]
    this.getBtnsList()
  },
  methods: {
    getBtnsList() {
      const menuCode = this.$route.query.menuCode
      if (!menuCode) return
      const buttonGroupCode = 'floorDetail'
      queryBtnList({ menuCode, buttonGroupCode }).then(res => {
        // res.data.groovyList
        this.buttons = (res.data && res.data.groovyList) || []
      })
    },
    hasPermission(code) {
      if (!this.isProduction) return true
      return this.buttons.filter(v => v.buttonCode === code).length > 0
    },
    dataChange(res) {
      this.tableData = (res && res.data && res.data.records) || []
    },
    gotoContent(row) {
      const { gotoType, categoryDTOList, filterId, gotoValue, gotoName } = row
      const obj = {
        'HELP_CENTER': '帮助中心',
        'HELP_CENTER_DETAIL': '帮助中心详情',
        'CUSTOM_PAGE': '自定义页面',
        'GOODS_CENTER_DETAIL': '商品详情',
        'ATLAS': '画册',
        'APPLY_PAGE': '应用页面',
        'OUTSIDE_LINK': '外部链接',
        'GOODS_CENTER_CATEGORY': '商品中心类目',
        'GOODS_CATE': '商品分类',
        'CUSTOMIZED_NEW_PRODUCT_SERIES': '定制新品系列',
        'DEFINE_TAB': '自定义导航',
        'SCHEME_CENTER': '方案中心',
        'PRODUCT_COMBINATION': '搭配套餐',
        'SCHEME_CUSTOMIZATION': '定制产品'
      }
      let result = obj[gotoType] || ''
      if (gotoType === 'OUTSIDE_LINK') {
        result += '：' + gotoValue
      } else {
        if (gotoName) {
          result += '：' + gotoName
        }
      }
      return result
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
    },
    // 新增/编辑基础信息
    handleEdit(row) {
      if (row && row.id) {
        queryRefCategoryList(row.id).then(res => {
          const categoryDTOList = (res.data && res.data.records) || []
          this.activeRowData = {
            ...row, ...{ categoryDTOList }
          }
          this.$nextTick(() => {
            this.showEdit = true
          })
        })
        return
      }
      this.activeRowData = ''
      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    // 删除处理
    handleDelete(row) {
      this.$confirm('此操作将永久删除当前所选内容, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = row.id
        delFloorDetail(id).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    /**
     * 排序
     * @param {Object} row 排序行
     * @param {string} type 移动类型(bottom 置底 ，top 置顶 ， moveDown 下移 ，  moveUp 上移)
    */
    handleSort(row, type) {
      if (this.sorting) return
      const now = Date.now()
      if (this.sortTime) {
        const diffTime = Math.floor((now - this.sortTime) / 1000)
        // 对比排序操作时间差，大于2s的可操作
        if (diffTime < 2) return
      }
      this.sortTime = now
      const params = {
        id: row.id,
        type
      }
      this.sorting = true
      updateSort(params).then(res => {
        this.sorting = false
        if (res.success === 1) {
          this.refreshTable()
        }
      }).catch(() => {
        this.sorting = false
      })
    }
  }
}

</script>
<style lang='scss' scoped>
  .item-title{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .alert-msg{
      flex: 1;
      font-size: 12px;
      color: #999;
      margin-left: 20px;
      font-weight: normal;
    }
  }
  .my-txt-btn{
    padding: 0 !important;
  }

 .cover-image{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      max-height: 70px;
      max-width: 100px;
      object-fit: cover;
    }
  }
</style>
